import {useReducer} from 'react';
import UseContextCom from './UseContextCom';
// useState 管理组件状态  useReducer 管理组件一些复杂逻辑的状态
// 对于的状态的类型约束
interface IState {
   count: number
};
// 对于Action对象的类型约束
type CounterAction =
  | { type: "reset" }
  | { type: "setCount"; value: IState["count"] }

const initialState: IState = { count: 0 };
// 状态处理函数 根据不同的type 执行不同的状态修改逻辑
function stateReducer(state: IState, action: CounterAction): IState {
  switch (action.type) {
    case "reset":
      return initialState;
    case "setCount":
      return { ...state, count: action.value };
    default:
      throw new Error("Unknown action");
  }
}

export default function UseReducerCom() {
    // stateReducer:处理状态的函数 initialState：初始状态
    // 返回值为 [状态, 修改状态的方法]
  const [state, dispatch] = useReducer(stateReducer, initialState);
  const addFive = () => dispatch({ type: "setCount", value: state.count + 5 });
  const reset = () => dispatch({ type: "reset" });

  return (
    <div>
      <h1>欢迎来到我的计数器</h1>

      <p>计数： {state.count}</p>
      <button onClick={addFive}>加 5</button>
      <button onClick={reset}>重置</button>
      <h2>useReducer组件下：</h2>
      {/* App -> UseReducerCom -> UseContextCom */}
      <UseContextCom />
    </div>
  );
}